package com.ysynzehao.service.impl;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.ysynzehao.bean.User;
import com.ysynzehao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * niuzehao
 * 2018/11/30 18:06.
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public User saveUser(User user) {
        mongoTemplate.save(user);
        return user;
    }

    /**
     * unless = "#result == null" 如果返回值为null,不缓存结果
     *
     * @param userId
     * @return
     */
    @Override
    public User getUser(String userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.findOne(query, User.class);
    }

    @Override
    public User updateUser(User user) {
        Query query = new Query(Criteria.where("userId").is(user.getUserId()));
        Update update = new Update().set("userName", user.getUserName());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, User.class);
        System.out.println(updateResult.getModifiedCount());
        return user;
    }

    @Override
    public void deleteUser(String userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        DeleteResult deleteResult = mongoTemplate.remove(query, User.class);
        System.out.println(deleteResult.getDeletedCount());
    }
}
